﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Resources;
using System.Web.Security;
namespace WebTeamplate
{
    public partial class Admin_User : BasePage
    {
        #region Fields
        public string urlDetail = "UserDetail.aspx";
        int count = 0;

        #endregion

        #region ViewState
        public int PageIndex
        {

            get
            {

                object o = ViewState["PageIndex"];

                if (o != null) return (int)o;

                return 0;

                //a default

            }

            set { ViewState["PageIndex"] = value; }

        }
        public string SortField
        {

            get
            {
                object o = ViewState["SortField"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortField"] = value; }

        }
        public string SortExpression
        {

            get
            {
                object o = ViewState["SortExpression"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortExpression"] = value; }

        }
        #endregion

        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSearch.ClientID);
            if (!Page.IsPostBack)
            {
                CommonFunction.LoadSubCate(drlGender,CommonFunction.DEFAULT_GENDER_CODE,true);
                LoadRoles();
                LoadData();
                txtUserName.Focus();
            }

        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitTextControl();
            InitData();
            this.imgUserNameSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgUserNameSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;
            this.imgNameSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgNameSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;
            imgUserNameSortDown.Click += new ImageClickEventHandler(imgUserNameSortDown_Click);
            imgUserNameSortUp.Click += new ImageClickEventHandler(imgUserNameSortUp_Click);
            imgNameSortDown.Click += new ImageClickEventHandler(imgNameSortDown_Click);
            imgNameSortUp.Click += new ImageClickEventHandler(imgNameSortUp_Click);
        }
        #endregion

        #region Methods
        private void LoadRoles()
        {
            //chkRoles.Items.Clear();
            string[] roles = Roles.GetAllRoles();
            if (roles.Length > 0)
            {
                Vw_aspnet_RolesResult objRoleMax = UserProfileUtil.GetMaxRole(this.userloginId, this.applicationName);
                foreach (string role in roles)
                {
                    Vw_aspnet_RolesResult objRole = UserProfileUtil.GetRoleByName(this.applicationName, role);
                    if (objRole.Level <= objRoleMax.Level)
                        drlRole.Items.Add(new ListItem(role, role));
                }
                drlRole.Items.Insert(0, new ListItem("- - -", string.Empty));               
            }
        }
        public void InitTextControl()
        {
            btnSearch.Text = Resources.Resource.LABEL_BUTTON_SEARCH;
            btnReset.Text = Resources.Resource.LABEL_BUTTON_RESET;
            btnAddNew.Text = Resources.Resource.LABEL_BUTTON_ADDNEW;
            
        }
        private void InitData()
        {
            this.PageIndex = 1;
            Pager1.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
           // CommonFunction.InitStatusPublishForRadioButtonList(rblStatus);
        }
        public void LoadData()
        {
            Vw_aspnet_RolesResult objRole = UserProfileUtil.GetMaxRole(this.userloginId, this.applicationName);
            if (objRole != null)
                maxRole = objRole.Level;
            hidListId.Value = string.Empty;
            hidListIdSelect.Value = string.Empty;
            UserProfile objUser = new UserProfile();
            //WHERE dbo.isGetUserForSupperAdmin(''' + @supperAdmin + ''',u.UserId)=1
            objUser.ApplicationName = this.applicationName;
            string condition = " where 1=1 ";
            if (txtEmail.Text != string.Empty)
                condition += " and m.Email like N'%" + txtEmail.Text + "%' ";
            if(drlGender.SelectedValue!=string.Empty)
                condition += " and p.Gender=" + drlGender.SelectedValue;
            //if (drlRole.SelectedValue != string.Empty)
            //    condition += " and p.Gender=" + drlGender.SelectedValue;
            if(txtName.Text!=string.Empty)
                condition += " and p.Name like N'%" + txtName.Text + "%' ";
            condition+=" and m.[IsApproved]=" + rblStatus.SelectedValue;
            //if (Roles.IsUserInRole(this.Page.User.Identity.Name, SystemEnum.SystemRole.SuperAdmin.ToString()))
            //    condition += " and dbo.isGetUserForSupperAdmin(1,u.UserId)=1";
            //else condition += " and dbo.isGetUserForSupperAdmin(0,u.UserId)=1";
            objUser.Condition = condition;
            objUser.ObjectPaging.PageIndex = this.PageIndex;
            objUser.ObjectPaging.PageSize = this.Pager1.PageSize;
            objUser.ObjectSortOrder.SortExpression = this.SortExpression;
            objUser.ObjectSortOrder.SortField = this.SortField;      
          
            List<UserProfileResult> lstResult = UserProfileUtil.SearchUserProfileSomeCondition(objUser);
            if (lstResult != null && lstResult.Count > 0)
                count = lstResult.Count;
            rptData.DataSource = lstResult;
            rptData.DataBind();
            Pager1.SetPaging(this.PageIndex, count, objUser.ToltalRow);
        }
        private void Delete(string id)
        {
             MembershipUser user = Membership.GetUser(new Guid(id));
             if (user != null)
             {
                 if (Membership.DeleteUser(user.UserName))
                 {
                     //delete Profile
                     UserProfileUtil.Delete(new Guid(user.ProviderUserKey.ToString()));
                     LoadData();
                 }                 
             }
        }
        public void ActiveUser(string id)
        {
            MembershipUser user = Membership.GetUser(new Guid(id));
            if (user != null)
            {
                if (user.IsApproved)
                    user.IsApproved = false;
                else
                    user.IsApproved = true;
                Membership.UpdateUser(user);
                LoadData();
            }


        }


        #endregion

        #region Events,Handler
        private int maxRole = 0;
        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                 UserProfileResult user = (UserProfileResult)e.Item.DataItem;
                 if (user == null)
                     return;
                 MembershipUser member = Membership.GetUser(user.UserId);
                 Vw_aspnet_RolesResult objRoleMax = UserProfileUtil.GetMaxRole(user.UserId, this.ApplicationName);
                 if (objRoleMax != null)
                 {
                     if (objRoleMax.Level > maxRole)
                     {
                         e.Item.Visible = false;
                         return;
                     }
                 }                 
                 else
                 {
                     e.Item.Visible = false;
                     return;
                 }
                 if (drlRole.SelectedValue != string.Empty)//check role
                 {
                     if (!Roles.IsUserInRole(member.UserName, drlRole.SelectedValue))
                     {
                         e.Item.Visible = false;
                         return;
                     }
                 }
                 Literal ltr = (Literal)e.Item.FindControl("ltrNo");
                 ltr.Text = (e.Item.ItemIndex + 1).ToString();
                 ltr = (Literal)e.Item.FindControl("ltrUserName");
                 ltr.Text = Server.HtmlEncode(member.UserName);
                 ltr = (Literal)e.Item.FindControl("ltrName");
                 string url = urlDetail + "?userid=" + user.UserId.ToString() + "&act=" + CommonFunction.DEFAULT_COMMAND_EDIT ;
                 ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(user.Name) + "</a>";
                // ltr.Text = Server.HtmlEncode(user.Name);
                 ltr = (Literal)e.Item.FindControl("ltrEmail");
                 ltr.Text = member.Email;
                 ImageButton imgButton = (ImageButton)e.Item.FindControl("btnPublish");
                 imgButton.CommandArgument = user.UserId.ToString();
                 if (member.IsApproved)
                     imgButton.ImageUrl = CommonFunction.DEFAULT_ACTIVE_IMAGEURL;
                 else
                     imgButton.ImageUrl = CommonFunction.DEFAULT_DEACTIVE_IMAGEURL;
                
                 
                 LinkButton lbtnDelete = (LinkButton)e.Item.FindControl("lbtnDelete");
                 lbtnDelete.Text = Resources.Resource.LABEL_DELETE;
                 lbtnDelete.CommandArgument = user.UserId.ToString();
                 HyperLink hplEdit = (HyperLink)e.Item.FindControl("hplEdit");
                 hplEdit.NavigateUrl = url;
                 if (this.UserloginId == user.UserId)
                 {
                     imgButton.Enabled = false;
                     lbtnDelete.Visible = false;
                 }
                 //else
                 //{
                 //    if (!Roles.IsUserInRole(this.Page.User.Identity.Name, SystemEnum.SystemRole.SuperAdmin.ToString()) && Roles.IsUserInRole(user.UserName, SystemEnum.SystemRole.SuperAdmin.ToString()))
                 //    {

                 //        imgButton.Enabled = false;
                 //        lbtnDelete.Visible = false;
                 //        hplEdit.Visible = false;
                 //    }
                 //}
               
                 hidListId.Value += user.UserId.ToString() + ";";
                 //if (!Roles.IsUserInRole(this.Page.User.Identity.Name, SystemEnum.SystemRole.SuperAdmin.ToString()) && Roles.IsUserInRole(user.UserName, SystemEnum.SystemRole.SuperAdmin.ToString()))
                 //{
                 //    e.Item.Visible = false;
                 //}
            }
        }
        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "Approved":
                    {
                        ActiveUser(id);
                        break;
                    }
                case "delete":
                    {
                        Delete(id);
                        break;
                    }

            }

        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.PageIndex = 1;
            LoadData();
        }
        void imgNameSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "Name";
            this.SortExpression = "DESC";
            LoadData();
        }
        void imgNameSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "Name";
            this.SortExpression = "ASC";
            LoadData();
        }

        void imgUserNameSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "UserName";
            this.SortExpression = "DESC";
            LoadData();
        }
        void imgUserNameSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "UserName";
            this.SortExpression = "ASC";
            LoadData();
        }

        protected void Pager1_PageIndexChanging(object obj, PagerControl.PageIndexChangeEventArgs e)
        {
            this.PageIndex = e.newPageIndex;
            LoadData();
        }
        protected void Pager1_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            LoadData();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(urlDetail);// + "?cateid=" + drlCategory.SelectedValue);
        }
        
        #endregion
    }
}
